package com.siyu.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {


    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeRequests(authorizeRequests ->
                        authorizeRequests
                                .antMatchers("/admin/**").hasRole("ADMIN") // 注意：这里通常使用 hasRole 而不是 hasAuthority
                                .antMatchers("/files/**").authenticated()
                                .anyRequest().authenticated()
                )
                .httpBasic(); // 这里直接调用 httpBasic() 来启用 HTTP Basic 认证

        // 注意：在 Spring Security 的某些版本中，您可能需要将 httpBasic() 调用放在不同的位置，
        // 或者使用不同的方法来启用 HTTP Basic 认证。但是，在 Spring Boot 2.6.1 的典型配置中，
        // 上面的代码应该是有效的。

        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}